package com.cloudkinto.service.template.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.entity.StorageDo;
import com.cloudkinto.entity.TailTrucksDo;
import com.cloudkinto.entity.TrucksTemplateDo;
import com.cloudkinto.dao.TrucksTemplateDao;
import com.cloudkinto.service.storage.StorageService;
import com.cloudkinto.service.storage.vo.StorageListRes;
import com.cloudkinto.service.tailtrucks.TailTrucksService;
import com.cloudkinto.service.template.TrucksTemplateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import com.cloudkinto.service.template.vo.*;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author zhangyy
 * @since 2020-10-26
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class TrucksTemplateServiceImpl extends ServiceImpl<TrucksTemplateDao, TrucksTemplateDo> implements TrucksTemplateService {
    @Autowired
    private TrucksTemplateDao dao;
    @Autowired
    private TailTrucksService tailTrucksService;
    @Autowired
    private StorageService storageService;

    @Override
    public SingleResult addInit() {
        List<StorageListRes> storageList = storageService.getList(new HashMap<>());
        return SingleResult.success(storageList);
    }

    @Override
    public void add(TrucksTemplateAddReq req, Long userId) {
        TrucksTemplateDo entityDo = new TrucksTemplateDo();
        BeanUtils.copyProperties(req, entityDo);
        handlerAddBefore(entityDo, userId);
        dao.insert(entityDo);
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(TrucksTemplateDo entityDo, Long userId) {
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(TrucksTemplateDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id) {
        Map map = new HashMap();
        map.put("detail",detail(id));
        Map map1 = (Map) addInit().getData();
        map.put("init",map1);
        return SingleResult.success(map);
    }

    @Override
    public TrucksTemplateUpdateReq update(TrucksTemplateUpdateReq req, Long userId) {
        TrucksTemplateDo entityDo = dao.selectById(req.getId());
        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
        return req;
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(TrucksTemplateDo entityDo, Long userId) {
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(TrucksTemplateDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        LambdaQueryWrapper<TailTrucksDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TailTrucksDo::getTrucksId, id);
        int integer = tailTrucksService.getBaseMapper().selectCount(wrapper);
        if (integer > 0) {
            throw new BizException(SysConstant.TrucksTemplate_Delete_Error);
        }
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(TrucksTemplateDo entityDo, Long userId) {
    }

    @Override
    public TrucksTemplateDetailRes detail(Long id) {
        TrucksTemplateDo entityDo = dao.selectById(id);
        TrucksTemplateDetailRes res = new TrucksTemplateDetailRes();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        return SingleResult.success("");
    }

    @Override
    public List<TrucksTemplatePageRes> getList(Map<String, String> map) {
        QueryWrapper<TrucksTemplateDo> wrapper = queryBuild(map);
        List<TrucksTemplateDo> list = this.list(wrapper);
        List<TrucksTemplatePageRes> result = handlerListAfter(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<TrucksTemplateDo> wrapper = queryBuild(map);
        IPage<TrucksTemplateDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<TrucksTemplatePageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    //查询分页列表之后对列表数据的处理
    private List<TrucksTemplatePageRes> handlerListAfter(List<TrucksTemplateDo> list) {
        List<TrucksTemplatePageRes> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(trucksTemplateDo -> {
                TrucksTemplatePageRes res = new TrucksTemplatePageRes();
                BeanUtils.copyProperties(trucksTemplateDo, res);
                StorageDo storageDo = storageService.getBaseMapper().selectById(trucksTemplateDo.getStorageId());
                if(storageDo != null){
                    res.setStorage(storageDo.getCode());
                }
                result.add(res);
            });
        }
        return result;
    }

    private IPage<TrucksTemplateDo> pageInit(Map<String, String> map) {
        IPage<TrucksTemplateDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<TrucksTemplateDo> queryBuild(Map<String, String> map) {
        QueryWrapper<TrucksTemplateDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.like("trucks_code", map.get("keyword"));
        }
        return wrapper.orderByDesc("id");
    }


}
